define(['require', 'exports', 'module', 'jquery', 'common/common', 'layer', 'dmuploader', 'sortable'],
    function (require, exports, module, $, common, layer) {

        var message = {
            addLog: function (item, status, str) {
                var d = new Date();
                var li = $('<li />', {'class': 'demo-' + status});

                var message = '[' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '] ';

                message += str;

                li.html(message);

                $(item).prepend(li);
            },

            addFile: function (item, i, file) {
                var url = window.URL || window.webkitURL;
                var imgURL = URL.createObjectURL(file);

                var tempId = $(item).attr('id');

                var template = '<div style="overflow: hidden;float: left;height: 186px;margin: 15px 0;" class="col-lg-3" id="' + tempId + i + '">' +
                    '<div class="remove"><i class="icon-remove"></i></div>' +
                    '<img class="imgs" id="' + tempId + '-img-' + i + '" style="width: 100%;height:100%;" src="' + imgURL + '">' +
                    '<div style="position: absolute;top: 50%;margin-left: -15px;z-index: 100;" class="col-lg-12">' +
                    '<div class="progress progress-striped active">' +
                    '<div class="progress-bar" role="progressbar" style="width: 0%;">' +
                    '<span class="sr-only">0% Complete</span>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>';

                var fc = $(item).attr('file-counter');
                if (!fc) {
                    $(item).empty();

                    i = 0;
                }

                i++;

                $(item).attr('file-counter', i);

                $(item).append(template);
            },

            updateFileStatus: function (item, i, status, message) {
                var tempId = $(item).attr('id');
                $('#' + tempId + i).find('span.demo-file-status').html(message).addClass('demo-file-status-' + status);
            },

            updateFileProgress: function (item, i, percent) {
                var tempId = $(item).attr('id');
                $('#' + tempId + i).find('div.progress-bar').width(percent);
                $('#' + tempId + i).find('span.sr-only').html(percent + ' Complete');

            },

            humanizeSize: function (size) {
                var i = Math.floor(Math.log(size) / Math.log(1024));
                return ( size / Math.pow(1024, i) ).toFixed(2) * 1 + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i];
            }
        };

        var upImg = function () {
            $('.drag-and-drop-zone').dmUploader({
                url: '/admin/upload/img/store',
                dataType: 'json',
                fileName: 'imgs',
                allowedTypes: 'image/*',
                onInit: function () {
                },
                onBeforeUpload: function (i) {
                    message.updateFileStatus($(this).parent().find('.show-files'), i, 'default', 'Uploading...');
                },
                onNewFile: function (i, file) {
                    var limit = $(this).attr('limit');
                    if (limit == undefined) {
                        limit = 10;
                    }
                    if ($(this).parent().find('.show-files').find('.imgs').length >= limit) {
                        layer.msg('只能上传' + limit + '张');
                        return false;
                    }
                    if (i >= 10) {
                        layer.msg('一次只能上传10张图');
                        return false;
                    } else {
                        message.addFile($(this).parent().find('.show-files'), i, file);
                    }
                },
                onComplete: function () {

                },
                onUploadProgress: function (i, percent) {
                    var percentStr = percent + '%';

                    message.updateFileProgress($(this).parent().find('.show-files'), i, percentStr);
                },
                onUploadSuccess: function (i, data) {
                    message.updateFileStatus($(this).parent().find('.show-files'), i, 'success', 'Upload Complete');

                    message.updateFileProgress($(this).parent().find('.show-files'), i, '100%');

                    var html = '';
                    if (data.code == 0) {
                        $('#' + $(this).parent().find('.show-files').attr('id') + '-img-' + i).attr('src', data.img_path);
                        html = '<div style="background: #000;text-align: center;color: #fff"><i class="icon-ok-sign"></i>上传成功</div>';
                    } else {
                        html = '<div style="background: #000;text-align: center;color: #fff"><i class="icon-ok-sign"></i>上传成功</div>';
                    }

                    $("#" + $(this).parent().find('.show-files').attr('id') + i).find('div.progress').parent().html(html);
                },
                onUploadError: function (i, messages) {
                    message.updateFileStatus($(this).parent().find('.show-files'), i, 'error', messages);
                },
                onFileTypeError: function (file) {
                },
                onFileSizeError: function (file) {
                },
                /*onFileExtError: function(file){
                 message.addLog('#demo-debug', 'error', 'File \'' + file.name + '\' has a Not Allowed Extension');
                 },*/
                onFallbackMode: function (message) {
                }
            });
        };

        var ajaxAddGoods = function () {
            $('.form-submit').bind('click', function () {
                var layerLoad = layer.load(1, {
                    shade: [0.1, '#fff'] //0.1透明度的白色背景
                });

                var formData = {};
                var formDataItem = $('.form-control');

                formDataItem.each(function (index, item) {
                    var __item = $(item);
                    if (__item.attr('name') != undefined) {
                        formData[__item.attr('name')] = __item.val();
                    }
                });

                console.log(formData);
                var goodsImgs = $('#goods_img').find('.imgs');
                var goodsDetail = $('#goods_detail').find('.imgs');

                if (goodsImgs.length == 0) {
                    layer.alert('请先上传商品图片');
                } else {
                    var imgs = [];
                    var sort = 1;
                    goodsImgs.each(function (index, img) {
                        var img_tmp = {};
                        img_tmp['imgUrl'] = $(img).attr('src');
                        img_tmp['imgId'] = $(img).attr('img-id');
                        img_tmp['sort'] = sort;
                        imgs.push(img_tmp);
                        sort++;
                    });

                    var illustrate = '';
                    goodsDetail.each(function (index, img) {
                        illustrate += $(img).attr('src') + '|';
                    });

                    formData['imgs'] = imgs;
                    formData['illustrate'] = illustrate;

                    common.ajaxPost('/store/goods/add', formData, function (error, data) {
                        if (error == null && data.code == 0) {
                            layer.msg('添加成功');
                            window.location.reload();
                        } else if (error == null && data.code != 0) {
                            layer.alert(data.msg);
                        } else {
                            layer.alert(error.statusText);
                        }
                        layer.close(layerLoad);
                    });
                }
            });
        };

        var ajaxUpdateGoods = function () {
            $('.form-submit').bind('click', function () {
                var layerLoad = layer.load(1, {
                    shade: [0.1, '#fff'] //0.1透明度的白色背景
                });

                var formData = {};
                var formDataItem = $('.form-control');

                formDataItem.each(function (index, item) {
                    var itemName = $(item).attr('name');
                    if (itemName != undefined) {
                        if (itemName == 'status') {
                            if ($(item).attr('checked') == 'checked') {
                                formData[itemName] = $(item).val();
                            }
                        } else {
                            formData[itemName] = $(item).val();
                        }
                    }
                });

                var goodsImgs = $('#goods_img').find('.imgs');
                var goodsDetail = $('#goods_detail').find('.imgs');

                if (goodsImgs.length == 0) {
                    layer.alert('请先上传商品图片');
                } else {
                    var imgs = [];
                    var sort = 1;
                    goodsImgs.each(function (index, img) {
                        var img_tmp = {};
                        img_tmp['imgUrl'] = $(img).attr('src');
                        img_tmp['imgId'] = $(img).attr('img-id');
                        img_tmp['sort'] = sort;

                        imgs.push(img_tmp);
                        sort++;
                    });

                    formData['imgs'] = imgs;

                    var illustrate = '';
                    goodsDetail.each(function (index, img) {
                        illustrate += $(img).attr('src') + '|';
                    });

                    formData['illustrate'] = illustrate;

                    common.ajaxPost('/store/goods/update', formData, function (error, data) {
                        if (error == null && data.code == 0) {
                            layer.msg('修改成功');
                            window.location.reload();
                        } else if (error == null && data.code != 0) {
                            layer.alert(data.msg);
                        } else {
                            layer.alert(error.statusText);
                        }
                        layer.close(layerLoad);
                    });
                }
            });
        };

        var updateGoodsStatus = function () {
            $('.update-status').bind('click', function () {
                var gid = $(this).attr('gid');
                var status = $(this).attr('status');

                var layerLoad = layer.load(1, {
                    shade: [0.1, '#fff'] //0.1透明度的白色背景
                });

                common.ajaxPost('/store/goods/update/status', {id: gid, status: status}, function (error, data) {
                    if (error == null && data.code == 0) {
                        layer.msg('修改成功');
                        window.location.reload();
                    } else if (error == null && data.code != 0) {
                        layer.alert(data.msg);
                    } else {
                        layer.alert(error.statusText);
                    }
                    layer.close(layerLoad);
                });
            });
        };


        var ajaxAddNav = function () {
            $('.form-submit').bind('click', function () {
                var layerLoad = layer.load(1, {
                    shade: [0.1, '#fff'] //0.1透明度的白色背景
                });

                var formData = {};
                var formDataItem = $('.form-control');

                formDataItem.each(function (index, item) {
                    var __item = $(item);
                    if (__item.attr('name') != undefined) {
                        formData[__item.attr('name')] = __item.val();
                    }
                });

                common.ajaxPost('/store/nav/add', formData, function (error, data) {
                    if (error == null && data.code == 0) {
                        layer.msg('添加成功');
                        window.location.reload();
                    } else if (error == null && data.code != 0) {
                        layer.alert(data.msg);
                    } else {
                        layer.alert(error.statusText);
                    }
                    layer.close(layerLoad);
                });

            });
        };


        var sortImg = function (item) {
            $(item).sortable({
                group: 'photo',
                animation: 150
            });
        };

        var removeImg = function (item) {
            $(item).on('click', '.remove', function () {
                $(this).parent().remove();
            });
        };
        exports.ajaxAddNav = ajaxAddNav;

        exports.updateGoodsStatus = updateGoodsStatus;

        exports.removeImg = removeImg;
        exports.upImg = upImg;
        exports.sortImg = sortImg;
        exports.ajaxAddGoods = ajaxAddGoods;
        exports.ajaxUpdateGoods = ajaxUpdateGoods;
    });